package com.gis.utils;

import java.io.*;
import java.nio.*;
import java.util.zip.*;

public class ZipExtraUtil {
    public static void unzip(String zipFilePath, String destDir) throws IOException {
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            destDirectory.mkdirs(); // 创建目标目录
        }

        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File newFile = new File(destDir, entry.getName());
                
                // 处理安全问题，防止 Zip Slip 漏洞
                String canonicalDestDir = destDirectory.getCanonicalPath();
                String canonicalNewFile = newFile.getCanonicalPath();
                if (!canonicalNewFile.startsWith(canonicalDestDir + File.separator)) {
                    throw new IOException("解压缩文件路径不安全: " + entry.getName());
                }

                if (entry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    // 确保父目录存在
                    new File(newFile.getParent()).mkdirs();

                    // 写入文件
                    try (FileOutputStream fos = new FileOutputStream(newFile);
                         BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, bytesRead);
                        }
                    }
                }
                zis.closeEntry();
            }
        }
    }
}
